/*
    auth:luochunneng
    createTime:2015-06-26
    name:imcfg
*/
require.config({
    baseUrl:'../',
    paths:{
        io: 'js/io',
        init:'init',
        imcfg:'js/imcfg'
    }
});

require(['io', 'init'], function($){
    console.log = function(){};
    var canvasObj = {};
    var contextObj = {};

    var CANVAS_WIDTH = document.body.clientWidth - 10;//window.screen.availWidth,
        CANVAS_HEIGHT = document.body.clientHeight - 10;//window.screen.availHeight;
    //用户绘画层
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    //当前用户显示层
    var picCanvas = document.getElementById('pic');
    var picContext = picCanvas.getContext('2d');

    //文字层
    var textCanvas = document.getElementById('text');
    var textContext = textCanvas.getContext('2d');

    //背景层
    var bgCanvas = document.getElementById('bg');
    var bgContext = bgCanvas.getContext('2d');

    canvasObj.canvas = canvas;
    canvasObj.picCanvas = picCanvas;
    canvasObj.textCanvas = textCanvas;
    canvasObj.bgCanvas = bgCanvas;

    contextObj.context = context;
    contextObj.picContext = picContext;
    contextObj.textContext = textContext;
    contextObj.bgContext = bgContext;

    var user = {};
        user.status = {};
        user.status.draw = false;
        user.status.start = false;
        user.status.textStart = false;
    var lines = {
        history:[],
        attr:{
            color:{
                red:{
                    value:255,
                    direction:1,
                    speed:4
                },
                green:{
                    value:0,
                    direction:-1,
                    speed:2
                },
                blue:{
                    value:99,
                    direction:1,
                    speed:3
                },
                alpha:1,
                rand:true
            },
            pen:{
                size:40,
                maxSize:100
            }
        },
        action:'line',
        actionColor:'#FF0066',
        lastLine:{},
        thisLine:{}
    };
    //控制层数据
    var textEvent = {
        'delete':{
            'title':'笔擦',
            'x':10,
            'y':10,
            'r':8,
            'color':'#0099FF'
        },
        'round':{
            'title':'圆',
            'x':10,
            'y':30,
            'r':8,
            'color':'#0099FF'
        },
        'line':{
            'title':'线',
            'x':10,
            'y':50,
            'r':8,
            'color':'#0099FF'
        },
        'pen':{
            'title':'画笔',
            'x':10,
            'y':70,
            'r':8,
            'color':'#0099FF'
        }
    };

    canvasInit();//初始化页面

    //获取坐标点
    var getPos = (function(){
        var canvasBox = canvas.getBoundingClientRect();
        canvasBox.xx = canvasBox.left * (canvas.width / canvasBox.width);
        canvasBox.yy = canvasBox.top * (canvas.height / canvasBox.height);
        return function(e){
            return {
                x: e.pageX - canvasBox.xx,
                y: e.pageY - canvasBox.yy
            };
        }
    })();

    //获取坐标点
    var getTextPos = (function(){
        var textCanvasBox = textCanvas.getBoundingClientRect();
        textCanvasBox.xx = textCanvasBox.left * (textCanvas.width / textCanvasBox.width);
        textCanvasBox.yy = textCanvasBox.top * (textCanvas.height / textCanvasBox.height);
        return function(e){
            return {
                x: e.pageX - textCanvasBox.xx,
                y: e.pageY - textCanvasBox.yy
            };
        }
    })();

    //mouse event
    mouseEventRegister();

    function mouseDown(e){
        if(event.button == 2){
            return 0;
        }
        if(event.ctrlKey){//取色
            var pos = getPos(e);
            var imageData = picContext.getImageData(pos.x, pos.y, 1, 1);
            // 获取该点像素数据
            var pixel = imageData.data;
            var color = lines.attr.color;
            if(pixel[3] == 0){
                color.rand = true;
                return 0;
            }
            color.red.value = pixel[0];
            color.green.value = pixel[1];
            color.blue.value = pixel[2];
            color.alpha = pixel[3];
            color.rand = false;
            return 0;
        }
        if(user.status.start){//如果已经下笔
            return mouseUp(e);
        }

        user.status.start = true;//下笔
        mouseEvent('down', e);
    }

    function mouseMove(e){
        if(user.status.start){//已经下笔
            mouseEvent('move', e);
        }
    }

    function mouseUp(e){
        if(user.status.start){//下笔
            mouseEvent('up', e);
        }
        lines.thisLine = false;
        user.status.start = false;
    }

    function mouseEvent(evt, e){
        var pos = getPos(e);
        switch(evt){
            case 'down':
                lines.thisLine = pos;
                pos.x += 0.1;
                draw('context', pos);//伪造起点
                break;
            case 'up':
                draw('picContext', pos);
                clearCanvas('context');//清除当前笔画
                break;
            case 'move':
                draw('context', pos);
                break;
        }
    }

    function genColor(){
        var col = lines.attr.color;
        if(col.rand){
            for(var i in col){
                var color = col[i];
                color.value += color.direction * color.speed;
                if(color.value > 255 || color.value < 0){
                    color.direction *= -1;
                    color.value += color.direction * color.speed;
                }
            }
        }
        return 'rgba('+ col.red.value +', '+ col.green.value +', '+ col.blue.value +', '+ col.alpha +')';
    }

    function clearCanvas(ctx){
        contextObj[ctx].clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    }

    /*
     * 动作实现
     * ID：目标
     * B：begin
     * E：end
    */
    function draw(id, pos){
        if(id == 'context') clearCanvas('context');
        var action = actionGet();
        switch(action.action){
            case 'line':
                pos.bx = lines.thisLine.x;
                pos.by = lines.thisLine.y;
                pos.color = genColor();
                break;
            case 'delete':
                id = 'picContext';
                break;
            case 'round':
                var bos = lines.thisLine;
                pos.r = Math.sqrt(Math.pow(pos.x - bos.x, 2) + Math.pow(pos.y - bos.y, 2));
                pos.ox = bos.x;
                pos.oy = bos.y;
                pos.color = genColor();
                break;
            case 'pen':
                lines.thisLine.x = pos.x;
                lines.thisLine.y = pos.y;
                id = 'picContext';
                pos.color = genColor();
                break;
        }
        painting($.id, id, action, pos);
    }

    function painting(ioid, id, action, pos){
        if(ioid === $.id && id != 'context') $.painting(ioid, id, action, pos);
        //初始化
        var context = contextObj[id];
        context.beginPath();
        //动作
        switch(action.action){
            case 'line':
                context.moveTo(pos.bx, pos.by);
                context.lineTo(pos.x, pos.y);
                context.strokeStyle = pos.color;
                context.stroke();
                break;
            case 'delete':
                context.globalCompositeOperation = "destination-out";
                context.moveTo(pos.x + 0.1, pos.y);
                context.lineTo(pos.x, pos.y);
                context.strokeStyle = '#000';
                context.stroke();
                context.globalCompositeOperation = "source-over";
                break;
            case 'round':
                context.strokeStyle = pos.color;
                context.arc(pos.ox, pos.oy, pos.r, 0, Math.PI*2, true);
                context.stroke();
                break;
            case 'pen':
                context.moveTo(pos.x - 0.1, pos.y);
                context.lineTo(pos.x, pos.y);
                context.strokeStyle = pos.color;
                context.stroke();
                break;
        }
    }

    function actionChange(e){
        var pos = getTextPos(e);
        for(var i in textEvent){
            var t = textEvent[i];
            if((t.x - t.r) <= pos.x && (t.y - t.r) <= pos.y && (t.x + t.r) >= pos.x && (t.y + t.r) >= pos.y){
                lines.action = i;
                drawControllText();
                return 0;
            }
        }

    }

    function actionGet(){
        /*
        altKey
        ctrlKey
        shiftKey
        button:0无，1左，2右，3左右，4中
        */
        var action = 'line';
        var data = {};

        action = lines.action;

        return {
            action:action,
            data:data
        };
    }

    function canvasInit(){
        //长宽设定
        canvas.width = CANVAS_WIDTH;
        canvas.height = CANVAS_HEIGHT;

        picCanvas.width = CANVAS_WIDTH;
        picCanvas.height = CANVAS_HEIGHT;

        textCanvas.width = CANVAS_WIDTH/4;
        textCanvas.height = CANVAS_HEIGHT/4;

        //背景平铺
        function bgSet(){
            var pattern = bgContext.createPattern(img, 'repeat');
            //bgContext.drawImage(img, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
            bgContext.fillStyle = pattern;
            bgContext.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        }
        var img = new Image();
        img.onreadystatechange = function(){
            if(img.readyState == "complete" || img.readyState == "loaded"){
                bgSet();
            }
        }
        img.onload = function(){
            if(img.complete == true){
                bgSet();
            }
        }
        img.onerror=function(){
            bgSet();
        }
        img.src = '../img/g.jpg';
        bgCanvas.width = CANVAS_WIDTH;
        bgCanvas.height = CANVAS_HEIGHT;

        drawControllText();

        context.lineWidth = lines.attr.pen.size;
        context.lineCap = "round";　　//设置线条两端为圆弧
        context.lineJoin = "round";　　//设置线条转折为圆弧
        //context.miterLimit

        picContext.lineWidth = lines.attr.pen.size;
        picContext.lineCap = "round";　　//设置线条两端为圆弧
        picContext.lineJoin = "round";　　//设置线条转折为圆弧
        //picContext.globalCompositeOperation = "destination-out";//擦除,source-over//默认
        //picContext.miterLimit
    }

    function drawControllText(){
        var evt;
        //
        for(var i in textEvent){
            evt = textEvent[i];
            addText(i, evt.title, evt.x, evt.y, evt.r, evt.color);
        }
        evt = textEvent[lines.action];
        addText(lines.action, evt.title, evt.x, evt.y, evt.r, lines.actionColor);
        function addText(evt, text, x, y, r, color){
            textContext.fillStyle = color;
            textContext.strokeStyle = color;
            textContext.beginPath();
            textContext.arc(x, y, r, 0, Math.PI*2, true); //Math.PI*2是JS计算方法，是圆
            textContext.closePath();
            textContext.fill();
            textContext.font = "14px Courier New";
            textContext.fillText(text, x + r * 2.5, y + r/2);
            //textContext.strokeText('按住Ctrl：橡皮擦功能', 10, CANVAS_HEIGHT - 10);
        }

        //线宽
        user.status.textStart = true;
        drawControllTextLineWidth();
        user.status.textStart = false;

    }
    function drawControllTextLineWidth(e){
        if (user.status.textStart) {
            var PADDING_WIDTH = 50;
            var PADDING_HEIGHT = 10;
            var pen = lines.attr.pen;
            var tx = textCanvas.width - PADDING_WIDTH;
            var ty = textCanvas.height - PADDING_HEIGHT;
            if(e){
                var pos = getTextPos(e);
                var h = Math.min(textCanvas.height - PADDING_HEIGHT, Math.max(PADDING_HEIGHT, pos.y - PADDING_HEIGHT));
                pen.size = pen.maxSize/(ty - PADDING_HEIGHT) * h;
                context.lineWidth = pen.size;
                picContext.lineWidth = pen.size;
            }
            textContext.clearRect(tx - PADDING_WIDTH - 10, 0, textCanvas.width, ty);
            textContext.beginPath();
            textContext.lineWidth = 8;
            textContext.lineCap = "butt";
            textContext.strokeStyle = '#00FF66';
            textContext.moveTo(tx, PADDING_HEIGHT);
            textContext.lineTo(tx, ty);
            textContext.stroke();
            //
            var penY = (ty - PADDING_HEIGHT)/pen.maxSize * pen.size;
            textContext.beginPath();
            textContext.lineCap = "butt";
            textContext.strokeStyle = '#FF0066';
            textContext.lineWidth = pen.size;
            textContext.moveTo(tx, penY);
            textContext.lineTo(tx, penY + 1);
            textContext.stroke();
        };
    }
    function actionMouseDown(e){
        var PADDING_WIDTH = 50;
        var PADDING_HEIGHT = 10;
        var tx = textCanvas.width - PADDING_WIDTH * 2;
        var ty = textCanvas.height - PADDING_HEIGHT;
        var pos = getTextPos(e);
        if(pos.x<tx){
            return 0;
        }
        if(user.status.textStart){//如果已经下笔
            return actionMouseUp(e);
        }

        user.status.textStart = true;//下笔
        drawControllTextLineWidth(e);
        user.status.textStart = false;//下笔
    }
    function actionMouseMove(e){
        if(user.status.textStart){//已经下笔
            drawControllTextLineWidth(e);
        }
    }
    function actionMouseUp(e){
        if(user.status.textStart){//下笔
            drawControllTextLineWidth(e);
        }
        user.status.textStart = false;
    }

    function mouseEventRegister(){
        //event
        if(typeof addEventListener == 'undefined'){
            canvas.attachEvent("onmousedown", mouseDown);
            canvas.attachEvent('onmousemove', mouseMove);
            canvas.attachEvent('onmouseup', mouseUp);
            canvas.attachEvent('ontouchstart', mouseDown);
            canvas.attachEvent('ontouchmove', mouseMove);
            canvas.attachEvent('ontouchend', mouseUp);

            textCanvas.attachEvent("onclick", actionChange);
            textCanvas.attachEvent("onmousedown", actionMouseDown);
            //textCanvas.attachEvent('onmousemove', actionMouseMove);
            //textCanvas.attachEvent('onmouseup', actionMouseUp);
        }else{
            canvas.addEventListener("mousedown", mouseDown, false);
            canvas.addEventListener('mousemove', mouseMove, false);
            canvas.addEventListener('mouseup', mouseUp, false);
            canvas.addEventListener('touchstart', mouseDown, false);
            canvas.addEventListener('touchmove', mouseMove, false);
            canvas.addEventListener('touchend', mouseUp, false);

            textCanvas.addEventListener('click', actionChange, false);
            textCanvas.addEventListener('mousedown', actionMouseDown);
            //textCanvas.addEventListener('mousemove', actionMouseMove);
            //textCanvas.addEventListener('mouseup', actionMouseUp);
        }
    }
    window.imcfg = {
        io:$,
        draw:draw,
        painting:painting
    };
    return window.imcfg;
});

